//#define __AVR_ATmega32__ 1

#include <stdlib.h>
#include <stdio.h>
#include <avr/io.h>
#include <avr/iom32.h> //Force eclipse to recognize this is a Mega32 device.
#include <avr/interrupt.h>
#include <avr/signal.h>
#include <avr/pgmspace.h>
#include <util/delay.h>
#include <string.h>

#include <inttypes.h>

#include <cdefs.h>

#include "uart.h"
#include "Interface.h"


#if (TERMINAL_BRAYS)
#define uart_clr() uart_putc(0x02); _delay_ms(200)
#else
#define uart_clr() uart_puts_P("\n\r\n\r\n\r")
#endif

#define uart_output_warn(s) uart_output(s)
#define uart_output_note(s) uart_output(s)

#define console_out_P(_s) uart_puts_P(_CONSOLE_TXT_); uart_puts_P(_s)
#define console_out(s) uart_puts_P(_CONSOLE_TXT_); uart_puts(s)

void HelpDialog(void)
{
	unsigned int i;
	console_out_P("Entering the help menu. ->\n\r");
	for(i=0; i<(sizeof(help)/2); i++){
		printf("[HELP]\t%c - %s\n\r",(unsigned int)cmds[i],help[i]);
	}
	uart_puts_P("[HELP]");
	console_out_P("[END OF HELP]");
}


int main(void)
{
    unsigned int c;
    unsigned int i=0;

    char vTmpString[255];

    uart_init(UART_BAUD_SELECT(UART_BAUD_RATE,F_CPU));

    sei();

    uart_clr();

	sprintf(vTmpString,"** %s [VERSION: %s.%s - BUILD: %s @ %s]",_APP_TITLE_,_APP_VER_,_APP_REV_,__DATE__,__TIME__);
	console_out(vTmpString);
	sprintf(vTmpString,"** Hardware v%s %s @ %sMhz - U(S)ART Communication v%s",_HARD_REV_,M_CPU,S_CPU,_UART_VER_);
	console_out(vTmpString);
	console_out_P(" ");
	sprintf(vTmpString,"** Welcome, User. System has been initialized and ready for use...");
	console_out(vTmpString);
	console_out_P(" ");

    for(;;)
    {

        c = uart_getc();
        if ( c & UART_NO_DATA )
        {
        }
        else
        {


            if ( c & UART_FRAME_ERROR )
            {
            	console_out_P("XX>> UART Frame Error! ");
				break;
            }
            if ( c & UART_OVERRUN_ERROR )
            {
            	console_out_P("XX>> UART Overrun Error!");
				break;
            }
            if ( c & UART_BUFFER_OVERFLOW )
            {
            	console_out_P("XX>> Buffer Overflow Error!");
				break;
            }
            uart_clr();
            //console_out_P(" ");
			sprintf(vTmpString,"Received \"%c\", Looking up function...", c);
			console_out(vTmpString);
			console_out_P(" ");


			/* **************** CMD_HELP ********************* */
			if ( c == (unsigned char)CMD_HELP)
			{
				RUN_HELP;
			}


			/* **************** CMD_HELLO ********************* */
			else if ( c == (unsigned char)CMD_HELLO)
			{
				printf("\n\rHello.");
			}
			else
			{
				console_out("No function found. Quitting...");
			}
		}
    }
    return 0;
}
